import React from 'react'
import { Form, Icon, Input, Button, message } from 'antd';
import './login.css'
import { SignIn } from '../api/sigin'
import { connect } from "react-redux";

class Login extends React.PureComponent{
    state={
        loading: false
    }
    handleSubmit = e => {
        e.preventDefault();
        const { handleogin, location, history } = this.props
        this.props.form.validateFields((err, values) => {
          if (!err) {
            this.setState({
                loading: true
            })
            SignIn(values).then(response=>{
                const { data } = response
                if(data.code === 0){

                    handleogin(data.data)

                    message.success('登录成功', 1, ()=>{
                       let redirect = location.state ? location.state.redirect : '/'

                       history.replace(redirect)
                    })
                } else {
                    message.error(data.msg)
                    this.setState({
                        loading: false
                    })
                }
            })
          }
        })
      }

    render() {
        const { getFieldDecorator } = this.props.form
        const { loading } = this.state
        return (
            <Form onSubmit={this.handleSubmit} className="login-form">
                <Form.Item label="用户名">
                    {getFieldDecorator('username', {
                    rules: [{ required: true, message: 'Please input your username!' }],
                    })(
                    <Input
                        prefix={<Icon type="user" style={{ color: 'rgba(0,0,0,.25)' }} />}
                        placeholder="Username"
                    />,
                    )}
                </Form.Item>
                <Form.Item label="密码">
                    {getFieldDecorator('password', {
                    rules: [{ required: true, message: 'Please input your Password!' }],
                    })(
                    <Input
                        prefix={<Icon type="lock" style={{ color: 'rgba(0,0,0,.25)' }} />}
                        type="password"
                        placeholder="Password"
                    />,
                    )}
                </Form.Item>
                <Form.Item>
                    <Button type="primary" htmlType="submit" className="login-form-button" loading={loading}>
                        登录
                    </Button>
                    <br />
                    Or <a href="http://localhost:3000/#/register" className="login-a">register now!</a>
                </Form.Item>
            </Form>
        )
    }
}

export default connect(
    null,
    (dispatch)=>({
        handleogin (user) {
            dispatch({
                type: 'LOGIN',
                user
            })
        }
    })
)(Form.create()(Login))